﻿using System;

namespace KryptecizerBase.Decryption
{
    /// <summary>
    /// Decryptor for TextBasedKryptOjects.
    /// Decrypts with Caesar-decryption-algorithm.
    /// </summary>
    public class CaesarDecryptor : KryptoTextDecryptor
    {
        /// <summary>
        /// Offset for decryption.
        /// </summary>
        private int _offset;

        /// <summary>
        /// Initializes a new instance of the <see cref="CaesarDecryptor"/> class.
        /// </summary>
        /// <param name="offset">The offset.</param>
        public CaesarDecryptor(int offset)
            : base()
        {
            _offset = -1 * offset;
        }

        /// <summary>
        /// Implementation of abstract method to decrypt the specified krypto text.
        /// Calls OnDecryptionProcessing method.
        /// </summary>
        /// <param name="kryptoText">The krypto text.</param>
        /// <returns>success</returns>
        protected override bool Decrypt(KryptoText kryptoText)
        {
            _KryptoText.Fill(String.Empty);
            string text = kryptoText.GetAsString().Replace(" ", String.Empty);
            KryptoText ktext = new KryptoText();
            text = KryptoText.EleminateSpecialSigns(text);
            ktext.Fill(text);
            try
            {
                double onePercent = ktext.Count / 100d;
                for (int i = 0; i < ktext.Count; i++)
                {
                    _KryptoText.Add(ktext.Shift(i, _offset));
                    OnDecryptionProcessing((int)((double)i / onePercent));
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
